package siyuan.run.nacos.security.oauth2.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import siyuan.run.nacos.security.oauth2.model.User;
import siyuan.run.nacos.security.oauth2.service.UserService;
import siyuan.run.nacos.security.oauth2.util.Result;

import java.util.List;

/**
 * @program: sy
 * @description:
 * @author: SY
 * @create: 2020-12-20 21:53
 **/
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping()
    public List<User> userList() {
        return userService.findAll();
    }

    @PreAuthorize("hasAuthority('ROLE_admin')")
    @GetMapping("/testauthority")
    public String testauthority() {
        return "ROLE_admin权限可以查看";
    }

    @PreAuthorize("hasRole('admin')")
    @GetMapping("/testrole")
    public String testrole() {
        return "admin可以查看";
    }

    @GetMapping("/register")
    public ResponseEntity<Result> register(User user) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        user.setPassword(encoder.encode(user.getPassword()));
        return ResponseEntity.ok(new Result(userService.save(user)));
    }

}
